#!/bin/bash
# -*- coding: utf-8 -*-
# @Date    : 2018-02-13

cdnName=$1
tarFile=$2
ftpPath=/data/inner_ftp/mir
baseCdnPath=/www/cdn
untarPath=${ftpPath}/tmp


colorPrint(){
	case $1 in
	g)
		echo -e "\033[32m$2\033[0m"
		;;
	r)
		echo -e "\033[31m$2\033[0m"
		;;
	b)
		echo -e "\033[34m$2\033[0m"
		;;
	*)
		echo "usage:`basename $0` 颜色 显示内容"
		;;
	esac
}

checkMD5(){
	for f in `tar -tf ${ftpPath}/${tarFile} | grep -v '/$'`;do
		sourceMD5=`md5sum ${untarPath}/$f | awk '{print $1}'`
		destMD5=`md5sum ${baseCdnPath}/${cdnName}/$f | awk '{print $1}'`
		[ $sourceMD5 == $destMD5 ] || colorPrint "r" "$f 的md5不一致" && exit 1
	done
}
	
checkFileExist(){
	ls $1 &> /dev/null
	if [ $? -ne 0 ];then
		echo "$1 不存在，退出脚本"
		exit 1
	fi
}

trueRsync(){
	# echo $3
	if [ $1 == "n" ];then
		colorPrint g "改变的文件列表如下:"
		for i in `echo $2 | tr ' ' '\n'`;do
			rsync -avPn ${untarPath}/$i/ $3/${i}/
		done
	else
		colorPrint g "开始同步:"
		for i in `echo $2 | tr ' ' '\n'`;do
			rsync -avPz ${untarPath}/$i/ $3/${i}/
		done
		cd ${baseCdnPath}
		bash cdn_sersync.sh ${cdnName}
	fi
}

rsyncToCdn(){
	checkFileExist ${ftpPath}/${tarFile}
	colorPrint g "${ftpPath}/${tarFile} 压缩包包含的文件列表如下："
	tar -tf ${ftpPath}/${tarFile}
	read -p "请确认是否同步(y/n):" choice
	case $choice in
		"y"|"Y")
			ls -l $untarPath &> /dev/null
			[ $? -ne 0 ] && mkdir $untarPath -pv
			[ `ls -ld $untarPath | awk '{print $2}'` -ne 2 ] && rm -rf ${untarPath}/*
			tar -xf ${ftpPath}/${tarFile} -C $untarPath
			dirList=`tar -tf ${ftpPath}/${tarFile} | awk -F"/" '{print $1}' | sort | uniq`
			trueRsync "n" "$dirList" ${baseCdnPath}/${cdnName}
			read -p "请确认是否同步(y/n):" cho
			[ $cho == "Y" -o $cho == "y" ] && trueRsync "z" "$dirList" ${baseCdnPath}/${cdnName} && checkMD5 || colorPrint "r" "同步失败"
			;;
		"N"|"n")
			colorPrint g "取消同步，退出程序"
			exit 1
			;;
		*)
			colorPrint r "输入错误，退出程序"
			exit 1
			;;
	esac

}

# 主入口
case $cdnName in
	"cqlltest"|"cqll"|"cqllbackup"|"cqllbackup5")
		rsyncToCdn 
		# checkMD5
		;;
	*)
		colorPrint g "用法:`basename $0` 前端目录名 tar包名"
		;;		
esac
